<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>seckill</title>

  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>

  <script src="https://cdn.bootcss.com/js-cookie/2.2.0/js.cookie.min.js"></script>

  <script src="https://cdn.bootcss.com/moment.js/2.22.2/moment.min.js"></script>
  <script src="https://cdn.bootcss.com/moment.js/2.22.2/locale/zh-cn.js"></script>

  <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <link href="https://cdn.bootcss.com/eonasdan-bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
  <script src="https://cdn.bootcss.com/eonasdan-bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>

  <link href="https://cdn.bootcss.com/datatables/1.10.19/css/dataTables.bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.bootcss.com/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.bootcss.com/datatables/1.10.19/js/dataTables.bootstrap.min.js"></script>

  <script src="https://cdn.bootcss.com/jquery-validate/1.19.0/jquery.validate.min.js"></script>
  <script src="https://cdn.bootcss.com/jquery-validate/1.19.0/localization/messages_zh.min.js"></script>
  
  <link href="/css/base.css" rel="stylesheet">
  <script src="/js/base.js"></script>

  <script>
    var millisecond;
    var activityValidator, detailValidator;

    $.validator.addMethod("price", function(value, element, params) {
      var checkReg = new RegExp('^[0-9]{1,9}(\.[0-9]{1,2})?$');
      return this.optional(element) || checkReg.test(value);
    } ,"请输入有效的金额");
    
    $.validator.setDefaults({
      errorPlacement: function(error, element) {
        if(element.parent().hasClass('input-group')) {
          error.appendTo(element.parent().parent());
        } else {
          error.appendTo(element.parent());
        }
      }
    });

    function initTable() {
      $('#activityTable').DataTable({
        "ajax": {
          "url": "/activity/list",
          "data": function (d) {
            d.productName = $('#searchText').val();
          }
        },
        "autoWidth": true,
        "processing": true,
        "serverSide": true,
        "ordering": false,
        "displayStart": 0,
        "pageLength": 10,
        "columns": [
          {"data": "sn"},
          {"data": "activityQuota"},
          {
            "data": "productId",
            "render": function (data, type, full) {
              return full.product.name;
            }
          },
          {
            "data": "productId",
            "render": function (data, type, full) {
              return '￥' + (full.product.price / 100).toFixed(2);
            }
          },
          {
            "data": "seckillPrice",
            "render": function (data, type, full) {
              return '￥' + (full.seckillPrice / 100).toFixed(2);
            }
          },
          {"data": "seckillMaxCount"},
          {"data": "startTime"},
          {
            "data": "sn",
            "className": "join-row",
            "render": function (data, type, full) {
              if (millisecond >= full.startTimeMillisecond) {
                return '<a class="btn btn-default btn-xs" href="javascript:;">join</a><span class="hidden">Not Started</span>';
              } else {
                return '<a class="btn btn-default btn-xs hidden" href="javascript:;">join</a><span>Not Started</span>';
              }
            }
          }
        ],
        "dom": "<'row'<'col-sm-12'tr>><'row'<'col-sm-5'i><'col-sm-7'p>>",
        "language": {
          "zeroRecords": "没有查询到数据",
          "info": "当前是第  _PAGE_ 页，共  _PAGES_ 页",
          "infoEmpty": "没有数据",
          "paginate": {
            "first": "首页",
            "last": "末页",
            "next": "下一页",
            "previous": "上一页"
          }
        }
      });
    }
    
    function changeActivityStatus() {
      var table = $('#activityTable').DataTable();
      $('#activityTable .join-row a:hidden').each(function(){
        var data = table.row($(this).closest('tr')).data();
        if(millisecond >= data.startTimeMillisecond) {
          $(this).removeClass('hidden').siblings().addClass('hidden');
        }
      });
    }

    $(function () {

      $.ajax({
        type: "GET",
        url: "/system/millisecond",
        dataType: "json",
        success: function(data){
          initTable();
          millisecond = data;
          $('#detailTime').html(moment(millisecond).format('YYYY-MM-DD HH:mm:ss'));
          setInterval(function(){
            millisecond += 1000;
            $('#detailTime').html(moment(millisecond).format('YYYY-MM-DD HH:mm:ss'));
            changeActivityStatus();
          },1000);
        }
      });
      
      activityValidator = $("#activityForm").validate();
      detailValidator = $("#detailForm").validate();

      $('#reload').click(function () {
        $('#activityTable').DataTable().ajax.reload();
      });

      $('#add').click(function () {
        $('#activityForm')[0].reset();
        activityValidator.resetForm();
        $('#creationModal').modal({
          keyboard: false
        });
      });

      $('#doAdd').click(function () {
        if (!$("#activityForm").valid()) {
          return;
        }
        $.ajax({
          type: "POST",
          url: "/activity/create",
          data: $('#activityForm').serialize()+"&seckillPrice="+encodeURIComponent(parseFloat($('#seckillPriceDigit').val())*100),
          dataType: "json",
          success: function(data) {
            if (data.result) {
              $('#activityTable').DataTable().ajax.reload();
              $('#creationModal').modal('hide');
            } else {
              alert("添加失败");
            }
          }
        });
      });

      $('#datetimepicker1').datetimepicker({
        locale: 'zh-cn',
        format: 'YYYY-MM-DD HH:mm:ss'
      });

      $.ajax({
        type: "GET",
        url: "/product/list",
        data: {},
        dataType: "json",
        success: function(data){
          if (data.result) {
            $('<option />').attr('value', '').attr('selected', 'selected').html(' -- 请选择 -- ').appendTo('#productId');
            $.each(data.result, function(){
              $('<option />').data('originalPrice', this.price).attr('value', this.id).html(this.name).appendTo('#productId');
            });

            var originalText = '/&nbsp;&nbsp;&nbsp;&nbsp;￥0.00';
            $('#originalPrice').html(originalText);
            $('#productId').change(function(){
              var price = $(this).find("option:selected").data('originalPrice');
              if (typeof price == 'undefined') {
                $('#originalPrice').html(originalText);
              } else {
                $('#originalPrice').html('/&nbsp;&nbsp;&nbsp;&nbsp;￥' + (price / 100).toFixed(2));
              }
            });
          }
        }
      });
      
      $('#activityTable').on("click", ".join-row a:visible", function(){
        var tr = $(this).closest('tr')[0];
        var data = $('#activityTable').DataTable().row(tr).data();

        $('#join').data("activity", data);
        $('.busi-product').html(data.product.name);
        $('.busi-price').html('￥' + (data.seckillPrice / 100) + '&nbsp;&nbsp;/&nbsp;&nbsp;￥' + (data.product.price / 100));
        $('.busi-count').html('&nbsp;&nbsp;/&nbsp;&nbsp;' + data.seckillMaxCount);
        $('.busi-result').html('');
        $('#detail-sn').val(data.sn);

        $('#detail-count').attr('max', data.seckillMaxCount);
        $('#detailForm')[0].reset();
        detailValidator.resetForm();

        $('#joinModal').modal({
          keyboard: false
        });
      });
      
      $('#join').click(function(){
        if (!$("#detailForm").valid()) {
          return;
        }
        $('#join').attr('disabled', 'disabled');
        $.ajax({
          type: "GET",
          url: "/activity/join",
          data: $('#detailForm').serialize(),
          dataType: "json",
          success: function(data){
            if (data.status == 0) {
              $('.busi-result').html('seckill successfully !');
            } else if (data.status == 1001) {
              $('.busi-result').html('活动已过期！');
            } else if (data.status == 1003) {
              $('.busi-result').html('没有库存了！');
            } else if (data.status == 1004) {
              $('.busi-result').html('你已经参与过了该活动！');
            }
          },
          complete: function (xhr, status) {
            $('#join').removeAttr('disabled');
          }
        });
      });
    });

  </script>
</head>
<body>
<h3 style="padding-left: 1%;">Welcome to join seckill activities. Now :
  <span id="detailTime"></span>
  <span style="display: inline-block; float: right; padding-right: 2%; font-size: 0.8em;">
    Hi, <span id="logined-user">${loginedUser.nickname}</span>.
    <a href="/logout">logout</a>
  </span>
</h3>

<div style="margin: 1%; width: 97%">
  <div class="row">
    <div class="col-sm-8">
      <a class="btn btn-default" href="javascript:;" id="add">
        <span class="glyphicon glyphicon-plus"></span>
      </a>
    </div>
    <div class="col-sm-4">
      <div class="input-group">
        <input type="text" class="form-control" id="searchText">
        <a class="input-group-addon btn" href="javascript:;" id="reload">查找</a>
      </div>
    </div>
  </div>

  <table id="activityTable" class="table table-striped" style="width: 100%;">
    <thead>
    <tr>
      <th>活动编号</th>
      <th>名额</th>
      <th>产品名称</th>
      <th>原价</th>
      <th>秒杀价</th>
      <th>最大秒杀数量</th>
      <th>秒杀活动开始时间</th>
      <th>活动状态</th>
    </tr>
    </thead>
  </table>
</div>

<!-- creation modal -->
<div class="modal fade" id="creationModal" data-backdrop="static">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span>&times;</span>
        </button>
        <h4 class="modal-title">New seckill activity</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" id="activityForm">
          <div class="form-group">
            <label for="activityQuota" class="col-sm-3 control-label">Activity Quota<span class="red">*</span></label>
            <div class="col-sm-9">
              <input type="text" class="form-control" id="activityQuota" name="activityQuota" placeholder="Quota" required digits="true" maxlength="9">
            </div>
          </div>
          <div class="form-group">
            <label for="productId" class="col-sm-3 control-label">Product<span class="red">*</span></label>
            <div class="col-sm-9">
              <select class="form-control" id="productId" name="productId" required></select>
            </div>
          </div>
          <div class="form-group">
            <label for="seckillPriceDigit" class="col-sm-3 control-label">Seckill Price<span class="red">*</span></label>
            <div class="col-sm-6">
              <div class="input-group">
                <div class="input-group-addon">￥</div>
                <input type="text" class="form-control" id="seckillPriceDigit" name="seckillPriceDigit" placeholder="Seckill Price" required price="true">
              </div>
            </div>
            <label id="originalPrice" class="col-sm-3 control-label" style="text-align: left; font-weight: normal;"></label>
          </div>
          <div class="form-group">
            <label for="seckillMaxCount" class="col-sm-3 control-label">Seckill Max Count<span class="red">*</span></label>
            <div class="col-sm-9">
              <input type="text" class="form-control" id="seckillMaxCount" name="seckillMaxCount" placeholder="Seckill Max Count" required digits="true" maxlength="9">
            </div>
          </div>
          <div class="form-group">
            <label for="startTime" class="col-sm-3 control-label">Activity Start Time<span class="red"></span></label>
            <div class="col-sm-9">
              <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" id="startTime" name="startTime" placeholder="Activity Start Time">
                <span class="input-group-addon">
                  <span class="glyphicon glyphicon-calendar"></span>
                </span>
              </div>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="doAdd">Save</button>
      </div>
    </div>
  </div>
</div>

<!-- join modal -->
<div class="modal fade" id="joinModal" data-backdrop="static">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span>&times;</span>
        </button>
        <h4 class="modal-title">Join seckill activity</h4>
      </div>
      <div class="modal-body">
        <div class="row" style="position: relative;">
          <div class="col-sm-8">
            <form class="form-horizontal" id="detailForm">
              <div class="form-group">
                <label class="col-sm-6" style="text-align: right;">Product：</label>
                <div class="col-sm-6 busi-product"></div>
              </div>
              <div class="form-group">
                <label class="col-sm-6" style="text-align: right;">Seckill Price / Original Price：</label>
                <div class="col-sm-6 busi-price"></div>
              </div>
              <div class="form-group">
                <label class="col-sm-6" style="text-align: right;">Seckill Count / Seckill Max Count：</label>
                <div class='col-sm-6'>
                  <input type="hidden" id="detail-sn" name="sn">
                  <input type='text' class="form-control input-sm" id="detail-count" name="count" value="1" style="width: 70%; display: inline-block;" required digits="true" min="1">
                  <span class="busi-count" style="width: 27%; display: inline-block;"></span>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-6" style="text-align: right;">Seckill Result：</label>
                <div class="col-sm-6 busi-result"></div>
              </div>
            </form>
          </div>
          <div class="col-sm-offset-1 col-sm-3" style="position: absolute; bottom: 20%; right: 0;">
            <button type="button" class="btn btn-success btn-join" id="join">Join</button>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

</body>
</html>